package com.scfire.index

import grails.converters.JSON
import grails.plugin.cache.CacheEvict
import grails.transaction.Transactional

import java.text.DateFormat
import java.text.DecimalFormat
import java.text.SimpleDateFormat

import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.apache.commons.logging.LogFactory
import org.springframework.transaction.annotation.Propagation

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.scfire.bean.ShareInfo
import com.scfire.content.*
import com.scfire.festival.*
import com.scfire.fund.FDonate
import com.scfire.fund.FRuler
import com.scfire.fund.FundPool
import com.scfire.project.*
import com.scfire.security.Member
import com.scfire.util.*
import com.scfire.weixin.*

/**
 * @author lenovo
 *
 */
class IndexController {
	
	def springSecurityService
	def authenticationTrustResolver
	
	def deviceInfoService
	def weiXinService
	def dataService
	def mongo
	String oauthCallBack = WeiXinConstants.oauth_pc_url+"?appid="+WeiXinConstants.appid_pc+"&redirect_uri="+URLEncoder.encode(WeiXinConstants.login_url+"?type=微信PC端")+"&response_type=code&scope=snsapi_login&state=STATE&#wechat_redirect"
	
			def LOG = LogFactory.getLog(IndexController.class)
	def grailsApplication
	def payService
	static int j=0
	DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	def saveDonate(){
		def donates = Donate.list()
		int i=0
		for(Donate d:donates){
			if(d.operate_fee_status=="true"){
				d.money = d.donate_fee+d.operate_fee
			}else{
				d.money = d.donate_fee
			}
			i++
			d.save(flush:true)
			println i
			
		}
		
	}
	
	public static Map forLock = new HashMap();
	
	public static Map forLockfundPool = new HashMap();
	
		//同步数据
	def checkFile(){
		Long x = new Date().getTime();
		try {
			
			int i=0;
			println "---------开始处理时间: " + new Date()+ "---------"
			String filePath=params.filePath
			File file=new File(filePath);
			if(file.isFile() && file.exists()){ //判断文件是否存在
				InputStreamReader read = new InputStreamReader(
				new FileInputStream(file));//考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				/*FileWriter   fw=new   FileWriter(new File("D:/tocheck/order.txt"));
				BufferedWriter   bw=new   BufferedWriter(fw);*/
				String lineTxt = null;
				
				while((lineTxt = bufferedReader.readLine()) != null){
					//System.out.println(lineTxt);
					String[] s = lineTxt.trim().split("`");
					i++;
					
					
					weixincallBack(s[1],s[2],s[3],s[4],s[5],s[6])
					
					/*Donate donate = Donate.findByOut_trade_no(s[4].trim())
					if(donate){
						
					}else{
					
					println "`"+s[1]+"`"+s[2]+"`"+s[3]+"`"+s[4]+"`"+s[5]+"`"+s[6]
					bw.write("`"+s[1]+"`"+s[2]+"`"+s[3]+"`"+s[4]+"`"+s[5]+"`"+s[6]);
					bw.newLine();
					bw.flush();
					
					}
					println i*/
				}
				/*bw.close();
				fw.close();*/
				read.close();
	}else{
		System.out.println("找不到指定的文件");
	}
	} catch (Exception e) {
		System.out.println("读取文件内容出错");
		e.printStackTrace();
	}
		
	println "---------结束处理时间: " + (new Date().getTime()-x)/1000+ "---------"
		
	}
	
	
	
	def weixincallBack(String s1,String s2,String s3,String s4,String s5,String s6){
		//String attach = WeiXinUtil.getValue(attach1 , "attach")
		String attach = s1.trim().replaceAll('\\\\','')
		/*
		String attach =     "{\"p\":\""+123+"\",\"m\":\""+1+"\","+
				"\"c\":\""+"true"+"\",\"df\":\""+1+"\","+
				"\"of\":\""+1+"\",\"s\":\""+-1+"\",\"dn\":\""+"asdfasdfasdf"+"\"}";*/
		def attachJSON
		try {
			 attachJSON = JSONObject.fromObject(attach.replaceAll('\\\\','') )
		} catch (Exception e) {
			e.printStackTrace()
		}
		String projectId = attachJSON.p
		String memberId = attachJSON.m
		boolean checked
		if("true".equalsIgnoreCase(attachJSON.c)){
			checked = true
		}else{
			checked = false
		}
		def donate_fee = attachJSON.df as float
		def operate_fee = attachJSON.of as float
		def subprojectid = attachJSON.s
		def donateNoNew = attachJSON.dn
		//String total_fee = WeiXinUtil.getValue(body , "total_fee")
		String total_fee=Float.valueOf(s2.trim())
		//String result_code = WeiXinUtil.getValue(body , "result_code")
		String result_code = "SUCCESS"
		//String out_trade_no = WeiXinUtil.getValue(body , "out_trade_no")
		String out_trade_no = s4.trim()
		//String openid = WeiXinUtil.getValue(body , "openid")
		String openid = s3.trim()
		//String transaction_id = WeiXinUtil.getValue(body , "transaction_id")
		String transaction_id = s5.trim()
		
		
		Donate donate = Donate.findByOut_trade_no(out_trade_no)
		if(donate){
			
		}else{
		j++
		   boolean flag
		   flag = weixinCallBacks(memberId, projectId, donate_fee, operate_fee, subprojectid, total_fee, out_trade_no, openid, transaction_id, checked, attach,donateNoNew,s6)
		   println flag
		}
	}
	
	static transactional = true
	/**
	 * 微信付款成功回调函数  --- 紧急优化解决事务问题
	 * @param null
	 * @return null
	 *
	 * **/
	@Transactional(propagation = Propagation.REQUIRED)
	def weixinCallBacks(String memberId,
				 String projectId,
				 float donate_fee,
				 float operate_fee,
				 String subprojectid,
				 String total_fee,
				 String out_trade_no,
				 String openid,
				 String transaction_id,
				 boolean checked,
				 String attach,
				 String donateNoNew,
				 String toDate){
				 boolean weixinflag = false
				 def donateurlTemp;
				 def projectTemp
				 if(forLock.get(projectId)==null){
					 forLock.put(projectId, new Object[0])
				 }
	 synchronized(forLock.get(projectId)) {
		 
		 println projectId +"--------"+forLock.get(projectId)
		 Thread t = Thread.currentThread()			 
		try{
			//判断是否已经有捐赠记录	
			Donate donate = Donate.findByOut_trade_no(out_trade_no)
			if(donate){
				println "aaaa"
				return true
			}
			def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		
			Member member = Member.findById(memberId)
			Project project = Project.findById(projectId)
			
			String donateurl = ""
			SubProject subproject
			
			//若是一起捐 则保存信息到subproject
			if(!subprojectid.equals("-1")){
				println subprojectid +"--------"
				subproject = SubProject.findById(subprojectid)
				subproject.subrest -= Float.valueOf(donate_fee)
				subproject.subdonate += Float.valueOf(donate_fee)
				subproject.subprogress = 100-(subproject.subrest/subproject.subamount)*100
				//4.金额计算，subProject rest计算，
				if(subproject.subrest <= 0){
					subproject.subrest = 0
					subproject.subprogress = 100
				}
				//subproject.save flush : true
				DBCollection projectCollection = db.getCollection("subProject")
				DBObject queryCondition= new BasicDBObject()
				queryCondition.put("_id",Integer.valueOf(subprojectid))
				BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("subrest", subproject.subrest)
					.append("subdonate", subproject.subdonate)
					.append("subprogress", subproject.subprogress)
					)
				
			  projectCollection.update(queryCondition, updateParameter,true,true)
			}
			long timestap = System.currentTimeMillis()/1000
			
			//捐赠信息
			
			donate = new Donate()
			donate.donateNo = UUID.randomUUID()
			donate.donateNoNew = donateNoNew
			donate.money = Float.valueOf(total_fee)
	
			donate.donate_fee = donate_fee
			donate.operate_fee = operate_fee
			donate.operate_fee_status = checked
			if(toDate!=null&&!toDate.equals("")){
				DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				donate.date = sdf.parse(toDate)
			}else{
			   donate.date = new Date()
			}
			donate.status = true
			donate.member = member
			donate.project = project
			//若是一起捐 保存捐赠信息到donate
			if(!subprojectid.equals("-1")) donate.subProject = subproject
			donate.out_trade_no = out_trade_no
			donate.openid = openid
			donate.transaction_id = transaction_id
			donate.attach = attach
			donate.type = "微信支付"
			
			DBCollection projectCollections = db.getCollection("donate")
			
			println donate.donateNo +"--++++++++++++"
			BasicDBObject doc_info = new BasicDBObject();
			try {
				doc_info.put("donateNo", donate.donateNo);
				doc_info.put("donateNoNew", donate.donateNoNew);
				doc_info.put("money",  String.valueOf(donate.money));
				doc_info.put("donate_fee", String.valueOf(donate.donate_fee));
				doc_info.put("operate_fee", String.valueOf(donate.operate_fee));
				doc_info.put("operate_fee_status", donate.operate_fee_status);
				doc_info.put("date", donate.date);
				doc_info.put("status", donate.status);
				doc_info.put("member", member?.id);
				doc_info.put("project", project.id);
				if(!subprojectid.equals("-1")) {
					doc_info.put("subProject", subproject.id);
				}
				doc_info.put("out_trade_no", donate.out_trade_no);
				doc_info.put("openid", donate.openid);
				doc_info.put("transaction_id", donate.transaction_id);
				doc_info.put("attach", donate.attach);
				doc_info.put("type", donate.type);
			} catch (Exception e) {
				println donate?.donateNo
				println donate?.donateNoNew
				println donate?.money
				println donate?.donate_fee
				println donate?.operate_fee
				println donate?.operate_fee_status
				println donate?.date
				println donate?.status
				println member?.id
				println  project?.id
				println donate?.out_trade_no
				println donate?.openid
				println donate?.transaction_id
				println donate?.attach
				println donate?.type
				println "*********************"
				e.printStackTrace()
			}
			
			
			
			println donate.donateNo +"--------"
			try {
				Donate d= Donate.last()
				doc_info.put("_id", d.id+1);
				projectCollections.insert(doc_info);
			} catch (Exception e) {
			println e.getMessage()
				Donate d1= Donate.last()
				doc_info.put("_id", d1.id+1);
				projectCollections.insert(doc_info);
			}
			donateurl = SCFIREConstants.PROJECT_DONATE_ELECTRONIC_INFO+donate.id
			//donateurl = "http://www.huodui.org/scfire/user/modifyMoblie"
			
			/*******************资金池配捐信息处理START*************************/
			//配捐信息获取
			println "---------begin FRuler time: " + new Date()+ "---------"+" thread id"+t.getName()+"---"+projectId
			FRuler fRuler = FRuler.findByProjectAndStatus(project,"true")
			//配捐标识
			boolean fdonateFlag = false
			//配捐金额
			int fdonatemoney = 0
			
			float regular = 0
			//如果项目有绑定资金池
			if(fRuler != null){
				FundPool fundPool = fRuler.fundPool
				if(forLockfundPool.get(String.valueOf(fundPool.id))==null){
					forLockfundPool.put(String.valueOf(fundPool.id), new Object[0])
				}
				synchronized(forLockfundPool.get(String.valueOf(fundPool.id))){
				BigDecimal bd = new BigDecimal(Float.toString(donate_fee))
				bd=bd*100;
				int donatemoney = bd.intValue();
				int bandfund = fRuler.bandfund
				int donatefund = fRuler.donatefund
				String fRegular = fRuler.regular
				String[] fRs = fRegular.split(":")
				regular = (Float.valueOf(fRs[1])/Float.valueOf(fRs[0])) //保留两位
				
				//计算可用金额 = 绑定配捐金额-实际已配捐金额
				int restfund = bandfund - donatefund
				if(restfund > 0){
					//可用金额根据配捐规则大于此次要配捐的金额,则进行配捐
					if(restfund >= donatemoney*regular){
						fdonatemoney = donatemoney*regular
						fRuler.donatefund += fdonatemoney
					}else{
						//最后剩余的全部进行配捐
						fdonatemoney = restfund
						fRuler.donatefund = bandfund
					}
					
					//添加配捐信息
					Donate donate1 = Donate.findByOut_trade_no(out_trade_no)
					FDonate fDonate = new FDonate()
					fDonate.donate_fee = fdonatemoney
					fDonate.status = "true"
					fDonate.date = new Date()
					fDonate.fundPool = fundPool
					fDonate.project = project
					fDonate.member = member
					fDonate.donate = donate1
					//fDonate.save flush:true
					
					DBCollection projectCollections2 = db.getCollection("FDonate")
					BasicDBObject doc_info2 = new BasicDBObject();
					
					doc_info2.put("donate_fee", fDonate.donate_fee);
					doc_info2.put("status",fDonate.status);
					doc_info2.put("date", fDonate.date);
					doc_info2.put("fundPool",fundPool?.id);
					doc_info2.put("project", project?.id);
					doc_info2.put("member", member?.id);
					doc_info2.put("donate",donate1?.id);
					doc_info2.put("version",0);
					FDonate fd= FDonate.last()
					doc_info2.put("_id", fd.id+1);
					try {
						projectCollections2.insert(doc_info2);
					} catch (Exception e) {
						FDonate fd1= FDonate.last()
						doc_info2.put("_id", fd1.id+1);
						projectCollections2.insert(doc_info2);
					}
					println "---------fDonate save " + new Date()+ "---------"+" thread id"+t.getName()
					//更新配捐规则中实际配捐金额信息
					fRuler.save flush:true
					println "---------fRuler save " + new Date()+ "---------"+" thread id"+t.getName()
					//更新资金池中实际已经配捐金额信息
					fundPool.donateActual += fdonatemoney
					DBCollection projectCollection = db.getCollection("fundPool")
					DBObject queryCondition= new BasicDBObject()
					queryCondition.put("_id",fundPool.id)
					BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("donateActual", fundPool.donateActual))
					projectCollection.update(queryCondition, updateParameter,true,true)
					//fundPool.save flush:true
					println "---------fundPool save " + new Date()+ "---------"+" thread id"+t.getName()
					fdonateFlag = true
				}
			  }
			}
			/*******************资金池配捐信息处理END*************************/
			weixinflag = true;
			donateurlTemp= donateurl
			projectTemp = project?.name
			
			println "---------begin project time: " + new Date()+ "---------"+" thread id"+t.getName()+"---"+projectId
			
			
			DBCollection projectCollection2 = db.getCollection("project")
			DBObject queryCondition2= new BasicDBObject()
			queryCondition2.put("_id",Integer.valueOf(projectId))
			
			String verified = project.verified
			if(fdonateFlag){
				project.rest = project.rest - (Float.valueOf(donate_fee)+Float.valueOf(fdonatemoney)/100)
				project.fDonateSize = project.fDonateSize++
				project.realAmount = project.realAmount + (Float.valueOf(donate_fee)+Float.valueOf(fdonatemoney)/100)
			}else{
				project.rest = project.rest - Float.valueOf(donate_fee)
				project.realAmount = project.realAmount+Float.valueOf(donate_fee)
			}
		   project.progress = 100-(project.rest/project.amount)*100
		   project.donateNum++
		   
		   BasicDBObject updateParameter2 =new BasicDBObject().append("\$set",new BasicDBObject().append("rest", project.rest)
																.append("fDonateSize", project.fDonateSize)
																.append("realAmount", project.realAmount)
																.append("progress", project.progress)
																.append("verified", project.verified)
																.append("donateNum", project.donateNum)
																)
															
		  projectCollection2.update(queryCondition2, updateParameter2,true,true)
		 
		   //2016年5月更新project表结构
		   //project.save flush : true
		   
		}catch(Exception e){
		println "***************"+out_trade_no+"***************"
			println "weixincallBack catch exception "+e.getMessage()
			return false
		}
		
	 }
	 return true
	}
	
	
	
	
	
	
	
/**
	 * 火堆首页
	 * @param null
	 * @return null
	 *
	 * **/	
    def index() {
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def user = springSecurityService.getCurrentUser()
		params.max = 8
				
		//List<Project> projects = new LinkedList<Project>()
		Banner banner = null
		def criteriaDonate = Donate.createCriteria()
		//def homes
		def posters
		def counts
		//dataService.downAliData(DateUtil.getDate("yyyy-MM-dd",-1));
		try{
			
			if("pc".equals(str)){
				posters = Bannerpc.findAll();
			}
			if("mobile".equals(str)){
				/*//加载项目信息
				homes = Home.list(sort:"position")
				for (def home:homes){
					projects.add(home.project)
				}*/
				banner = Banner.first()
			}
			
		}catch(Exception e){
			log.error("scfire catch exception. "+e.getMessage())
		}
		counts = Donate.count();
		log.info(counts+"-----------------");
		List<Project> projects = new ArrayList<Project>()
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "indexpc", model: [posters:posters, index:1, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
				if("mobile".equals(str)){//首页可能不具备获取用户的能力，而手机登陆能获取用户
				
					
					//微信分享参数
					def url = WeiXinConstants.server+"/"
					if(request.getQueryString()){
						url = (url + "?" + request.getQueryString())
					}
					Map map = weiXinService.jsapiTicketSign(url)
					def noncestr = map.get("noncestr")
					def jsapi_ticket = map.get("jsapi_ticket")
					def timestamp = map.get("timestamp")
					def sign = map.get("sign")
					def imgUrl =  WeiXinConstants.server+"/images/scfire.png"
					def shareUrl = WeiXinConstants.server
					
					render view: "indexmb", model: [banner:banner,user:(Member)user,counts:counts,str:str,
						appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl]
				}
			}
			json {
				
			}
		}
	}
	/**
	 * 获取捐赠的总数
	 */
	def getCountsJson(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def counts
		withFormat {
			json {
				JSONArray countjson = new JSONArray()
				JSONObject json = new JSONObject()
			    counts = Donate.count();
				json.put("counts", counts);
				countjson.add(json);
				render countjson as JSON
		     }
		}
	}
	
	
	
	/**
	 * 火堆首页
	 * @param null
	 * @return null
	 *
	 * **/
	def pc_index() {
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def user = springSecurityService.getCurrentUser()
		params.max = 8
		Banner banner = null
		def counts
		try{
			counts = Donate.count();
			banner = Banner.first()
		}catch(Exception e){
			LOG.error("scfire catch exception. "+e.getMessage())
		}
		withFormat {
			html {
					render view: "indexmb", model: [banner:banner,counts:counts,str:str]
			}
		}
	}
	
	def toMobile(){
		withFormat {
			html {
					render view: "toMobile"
			}
		}
		
	}
	
	
	/**
	 * 火堆首页
	 * @param null
	 * @return null
	 *
	 * **/
	def waiter() {
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		params.max = 6
				
		List<Project> projects = new LinkedList<Project>()
		Banner banner = null
		
		try{
			//加载项目信息
			banner = Banner.first()
			
		}catch(Exception e){
			LOG.error("scfire catch exception. "+e.getMessage())
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "waitmb", model: [banner:banner]
				}
				if("mobile".equals(str)){
					render view: "waitmb", model: [banner:banner]
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * pc端产品展示页
	 */
	def product(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "product_pc", model:[index:2, oauthCallBack:oauthCallBack]
				}
				if("mobile".equals(str)){
					render view: "product_pc", model:[index:2, oauthCallBack:oauthCallBack]
				}
			}
			json {
				
			}
		}
	}
	/**
	 * pc端案例
	 */
	def cases(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		def cates = Channelpc.findAllByCategory(SCFIREConstants.CATE_CHANNEL_CASE);
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "cases_pc", model:[cates:cates, index:4, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
				if("mobile".equals(str)){
					render view: "cases_pc", model:[cates:cates, index:4, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * pc端动态
	 */
	def dynamic(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		def cates = Channelpc.findAllByCategory(SCFIREConstants.CATE_CHANNEL_DYNAMIC);
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "dynamic_pc", model:[cates:cates, index:3, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
				if("mobile".equals(str)){
					render view: "dynamic_pc", model:[cates:cates, index:3, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
			}
			json {
				
			}
		}
	}
	/**
	 * pc端伙伴
	 */
	def companion(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		def partners = Channelpartnerpc.findAllByCategory(SCFIREConstants.CATE_CHANNEL_PARTNER);
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view:"companion_pc", model:[partners:partners, index:5, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
				if("mobile".equals(str)){
					render view:"companion_pc", model:[partners:partners, index:5, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
			}
			json {
				
			}
		}
	}
	
	def about(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		def partners = Channelpartnerpc.findByCategory(SCFIREConstants.CATE_CHANNEL_ABOUT);
		def abouts = Channelpc.findByCategory(SCFIREConstants.CATE_CHANNEL_ABOUT);
		def about = Articlepc.findByTag('about');
		def joinUs = Articlepc.findByTag('joinUs');
		def diaryMap = new HashMap<Integer, SortedSet<Diary>>();
		def Alldiary = Diary.findAll();
		for(Diary diary : Alldiary){//按照年份进行迭代
			int year = diary.date.getYear()+1900;
			SortedSet diaries  = diaryMap.get(year);
			if(diaries != null){
				diaries.add(diary);
			}
			else{
				diaries = new TreeSet<Diary>();
				diaries.add(diary);
				diaryMap.put(year, diaries);
			}
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view:"about_pc", model:[partners:partners,diarymap:diaryMap, about:about, joinUs:joinUs, index:6, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
				if("mobile".equals(str)){
					render view:"about_pc", model:[partners:partners, diarymap:diaryMap, about:about, joinUs:joinUs, index:6, oauthCallBack:oauthCallBack]//index 指示哪一个标签是active的
				}
			}
			json {
				
			}
		}
	}
	
	def ArticleList(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String channelId = params.channelId;
		def articles
		params.max = 20
		params.offset = "0"
		try {
			def SCriteria = Articlepc.createCriteria()
			def fcd={
				eq("channelpc", Integer.parseInt(channelId))
				order("date","desc")
				firstResult(Integer.parseInt(params.offset))
			}
			articles = SCriteria.list(params, fcd);
		} catch (Exception e) {
			LOG.error("query article list catch error ");
		}
		
		withFormat {
			html {
				render (articles as JSON)
			}
			json {
				JSONArray articlejson = new JSONArray()
				for(Articlepc article:articles){
					JSONObject json = new JSONObject()
					json.put("id",article.id)
					json.put("title", article.title)
					json.put("description", article.description)
					json.put("img", "'/scfire/project/imgRead?img="+article.img+"'")
					json.put("date",(1900+article.date.getYear())+"-"+(article.date.getMonth()+1)+"-"+article.date.getDate()+" "+article.date.getHours()+":"+article.date.getMinutes())
					articlejson.add(json)
				}
				render articlejson as JSON
			}
		}
	}
	
	
	/**
	 * 春节活动页面
	 * @return
	 */
	def festivalActivity(){
		//获得一个0-99的数
		Random random = new Random(System.currentTimeMillis()%47);
		int num = random.nextInt(100);
		println num
		int pageIndex = 0;
		String ticket = ""
		//红包相关信息
		def redElp =  RedEnvelope.get(1);
		boolean ticketFlag = redElp.stats;
		
		//分配概率区间
		//红包功能开启的情况
		if(ticketFlag){
			if(num <= 15){//15%
				pageIndex = 1;
				ticket = redElp.ticket;
			}
			else if(num <= 40){//25%
				pageIndex = 2;
			}
			else if(num <= 60){//20%
				pageIndex = 3;
			}
			else if(num <= 80) {//20%
				pageIndex = 4;
			}
			else{//20%
				pageIndex = 5;
			}
		}//关闭的情况
		else{
			if(num < 40){//40%
				pageIndex = 2;
			}
			else if(num < 60){//20%
				pageIndex = 3;
			}
			else if(num <= 80){//20%
				pageIndex = 4;
			}
			else{//20%
				pageIndex = 5;
			}
		}
		
		//分享传播监控
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def openid = user.openid
		JSONObject authinfo = new JSONObject();
		authinfo.put("openid", user.openid);
		authinfo.put("nickname", user.nickname);
		authinfo.put("province", user.province);
		authinfo.put("city", user.city);
		authinfo.put("country", user.country);
		authinfo.put("headimgurl", user.headimgurl);
		authinfo.put("unionid", user.unionid);
		authinfo.put("sex", user.sex);
		
		String url = ""
		if(request.getQueryString()){//解决多次连续分享的连接验证问题
			url = WeiXinConstants.server + "/index/festivalActivity?"+request.getQueryString()
		}
		else{
			url = WeiXinConstants.server + "/index/festivalActivity?festid=1"
		}
		//分享模块
		ShareInfo share = new ShareInfo(weiXinService,
										 url,//分享源页面地址（发起分享的页面地址）
										 "陈数邀你一起摇出童年春节记忆",//分享标题
										 "春节渐近，儿时那期盼过年的心情你是否还记得？", //分享描述
										 WeiXinConstants.server + "/index/festivalActivity?festid=1",//分享他人的目标地址
										 WeiXinConstants.server+"/images/chenshu-min.jpg",//分享的图片
										 "#");//分享后的重定向地址
		
		render view:"h5Index", model:[pageIndex:pageIndex, ticket:ticket, shareinfo:share,authinfo:authinfo,openid:openid]
	}
	
	
	
	
	
	/**
	 * 火堆首页异步加载项目信息
	 * @param null
	 * @return null
	 *
	 * **/
	//@Cacheable(value='cachememory')
	def indexPoolJSON() {
		
				
		JSONArray poolprojects = new JSONArray()
		//加载项目信息
		def pools = FundPool.list(sort:"totalCount",order:"desc")
		int i=0
		for (def pool:pools){
			
				FundPool funpool = pool
				JSONObject json = new JSONObject()
				json.put("id",funpool.id)
				json.put("name",funpool.name)
				json.put("type",funpool.type)
				json.put("img",funpool.coverPic)
				json.put("coverPic",funpool.coverPic)
				json.put("fullName",funpool.fullName)
				DecimalFormat decimalFormat=new DecimalFormat("#0.00")
				json.put("totalCount",decimalFormat.format(funpool.totalCount/100))
				poolprojects.add(json)
				i++
				if(i==3){
					break;
				}
			
		
		}
		
		render poolprojects as JSON
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 火堆首页异步加载项目信息
	 * @param null
	 * @return null
	 *
	 * **/
	// @Cacheable(value='cachememory')
	def indexJSON() {
				
		JSONArray projects = new JSONArray()	
		//加载项目信息
		params.sort = "position"
		def homes = Home.list(params)
		
		for (def home:homes){
			JSONObject json = new JSONObject()
			Project project = home.project
			//LOG.info(homes);
			/*float totalamout = 0.0;
			for(def donate:project.donates){
				totalamout += donate.donate_fee
			}
			project.rest = project.amount - totalamout;
			if(project.rest <= 0){
				project.rest = 0
				project.progress = 100
			}else{
				project.progress = 100-(project.rest/project.amount)*100
			}	*/		
						
			json.put("id",project.id)
			json.put("img",project.img)
			json.put("name",project.name)
			json.put("progress",project.progress)
			json.put("verified",project.verified)
			json.put("donatenum",project.donateNum)
			DecimalFormat decimalFormat=new DecimalFormat("#0.00")
			String donatemoney = decimalFormat.format(project.realAmount)
			json.put("donatemoney",donatemoney)
			json.put("description",project.description)	
			projects.add(json)
		}
		render projects as JSON
		
	}
	
	/**
	 * 火堆首页异步加载缓存释放
	 * @param null
	 * @return null
	 *
	 * **/
	@CacheEvict(value='cachememory',allEntries=true)
	def indexJSONEvict() {
		
		println "--------------release cache memory-----------------"
		
	}
}
